package com.dqp.cslggroup.JWXT;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.Api.xxmhApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.Features.Setting;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.DialogView;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.academic;
import com.dqp.cslggroup.bean.avatar;
import com.dqp.cslggroup.bean.event;
import com.dqp.cslggroup.bean.student;
import com.dqp.cslggroup.personal_center;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class JWXT_main extends BaseActivity {
    private Map<String, String> cookies = null;
    private Intent intent;
    private ImageView head;
    private TextView name, gpa, zong, tg, wg;
    private String xm_text, xy_text, zy_text, stuNum, rxnf, syd;
    private ViewStub viewstub_loading;
    ExecutorService threadPool = Executors.newFixedThreadPool(5);
    private boolean loading = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jwxt_main);
        EventBus.getDefault().register(this);
        initCmp();
        getCookies(false);
    }

    public void getCookies(boolean refresh) {
        Map<String, String> map = SharedPreferencesUtil.getMap(this, "cookies");
        long time = SharedPreferencesUtil.getLongSp(this, "cookiesTime", 0);
        long nowTime = Calendar.getInstance().getTimeInMillis();
        long x = GetTimeUtil.minuteDifference(nowTime, time);
        if (x < 10 && !refresh) {
            cookies = map;
            info();
        } else {
            String xxmh = SharedPreferencesUtil.getStringSp(this, "password_XXMH", null);
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
//            String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
            if (!StringUtil.isEmpty(xxmh, sno)) {
                viewstub_loading.setVisibility(View.VISIBLE);
                threadPool.execute(() -> {
                    loading = true;
                    JSONObject jsonObject = xxmhApi.login(sno, xxmh, "0");
                    if (Result.jsonResultIsTure(jsonObject)) {
                        JSONObject object = jsonObject.getJSONObject("info");
                        Map<String, String> xxmhCookies = JSONObject.parseObject(object.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        if (xxmhCookies == null || xxmhCookies.size() < 2) return;
                        object = xxmhApi.jwxt(xxmhCookies);
                        if (Result.jsonResultIsTure(object)) {
                            cookies = xxmhCookies;
                            info();
                            CookiesUtil.save(this, cookies);
                            EventBus.getDefault().post(new MessageEvent("JWXT_main", 12, refresh));
                        }
                    } else if (jsonObject.containsKey("resultMsg") && jsonObject.getJSONObject("resultMsg").containsKey("密码错误")) {
                        alertDialog("密码错误", "您绑定的信息门户账号密码错误，您近期是否进行了密码更改？" +
                                "现已无法正常使用该模块功能，为确保正常使用请前往设置重新绑定！");
                    }
                    loading = false;
                });
            } else {
                alertDialog("账号未绑定", "检测到您绑定的信息门户、教务系统账号或密码信息缺失，无法正常使用该模块功能，" +
                        "为确保正常使用请前往设置进行绑定！");
            }
        }
    }


    public void info() {
        List<academic> academicList = MyApplication.getDaoInstant().getAcademicDao().loadAll();
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (academicList != null && academicList.size() > 0 && studentList != null && studentList.size() > 0) {
            EventBus.getDefault().post(new MessageEvent("JWXT_main", 10, null));
        } else
            threadPool.execute(() -> {
                loading = true;
                JSONObject jsonObject = jwxtApi.info(stuNum, cookies);
                if (Result.jsonResultIsTure(jsonObject)) {
                    if (jsonObject.containsKey("academic")) {
                        JSONObject object = jsonObject.getJSONObject("academic");
                        academic academic = object.toJavaObject(academic.class);
                        if (academic != null) {
                            MyApplication.getDaoInstant().getAcademicDao().deleteAll();
                            MyApplication.getDaoInstant().getAcademicDao().insert(academic);
                        }
                    }
                    if (jsonObject.containsKey("info")) {
                        JSONObject object = jsonObject.getJSONObject("info");
                        student student = new student();
                        student.setXh(object.getString("sno"));
                        student.setXm(object.getString("name"));
                        student.setXy(object.getString("faculty"));
                        student.setZy(object.getString("specialities"));
                        student.setRxnf(object.getString("grade"));
                        student.setSf(object.getString("province"));
                        MyApplication.getDaoInstant().getStudentDao().insertOrReplace(student);
                    }
                    if (jsonObject.containsKey("head")) {
                        avatar avatar = new avatar();
                        avatar.setBytes(jsonObject.getBytes("head"));
                        MyApplication.getDaoInstant().getAvatarDao().deleteAll();
                        if (avatar.getBytes() != null)
                            MyApplication.getDaoInstant().getAvatarDao().insertOrReplace(avatar);
                    }
                    EventBus.getDefault().post(new MessageEvent("JWXT_main", 10, null));
                }
                loading = false;
            });
    }

    public void course(String sno) {
        viewstub_loading.setVisibility(View.VISIBLE);
        threadPool.execute(() -> {
            loading = true;
            int term = 0;
            int year = GetTimeUtil.getYear();
            int month = GetTimeUtil.getMonth();
            if (month % 2 == 0 && month < 7) {
                year--;
            }
            if (month >= 8 || month < 2) {
                term = 1;
            } else term = 2;
            JSONObject jsonObject = jwxtApi.course(sno, year, term, cookies);
            if (Result.jsonResultIsTure(jsonObject))
                EventBus.getDefault().post(new MessageEvent("JWXT_main", 2, null));
            else EventBus.getDefault().post(new MessageEvent("JWXT_main", 3, jsonObject.getString("resultMsg")));
            loading = false;
        });
    }

    public void course(String sno, int year, int term) {
        viewstub_loading.setVisibility(View.VISIBLE);
        threadPool.execute(() -> {
            loading = true;
            JSONObject jsonObject = jwxtApi.course(sno, year, term, cookies);
            if (Result.jsonResultIsTure(jsonObject))
                EventBus.getDefault().post(new MessageEvent("JWXT_main", 2, null));
            else EventBus.getDefault().post(new MessageEvent("JWXT_main", 3, jsonObject.getString("resultMsg")));
            loading = false;
        });
    }

    @SuppressLint("HandlerLeak")
    private void initCmp() {
        Toolbar toolbar = findViewById(R.id.jwxt_main_toolbars);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        TextView re = toolbar.findViewById(R.id.jwxt_main_out);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        head = findViewById(R.id.jwxt_main_head);
        name = findViewById(R.id.jwxt_main_name);
        gpa = findViewById(R.id.text_gpa);
        zong = findViewById(R.id.text_zong);
        tg = findViewById(R.id.text_tg);
        wg = findViewById(R.id.text_wg);
        viewstub_loading = findViewById(R.id.viewstub_loading);
//        head.setOnClickListener(v -> {
//            intent = new Intent(JWXT_main.this, personal_center.class);
//            startActivity(intent);
//        });
        re.setOnClickListener(v1 -> {
            viewstub_loading.setVisibility(View.VISIBLE);
            getCookies(true);
        });
        stuNum = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
        if (StringUtil.isEmpty(stuNum, 9)) {
            ToastUtil.showToast("🤦‍未绑定身份信息！");
            finish();
        }
    }

    @SuppressLint("SetTextI18n")
    private void initText() {
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList.size() > 0) {
            xm_text = studentList.get(0).getXm();
            xy_text = studentList.get(0).getXy();
            zy_text = studentList.get(0).getZy();
            rxnf = studentList.get(0).getRxnf();
            syd = studentList.get(0).getSyd();
            if (StringUtil.isEmpty(xm_text, xy_text, zy_text)) {
                MyApplication.getDaoInstant().getStudentDao().deleteAll();
            } else name.setText(xm_text + "\n" + xy_text + "\n" + zy_text);
        }
        List<avatar> avatars = MyApplication.getDaoInstant().getAvatarDao().loadAll();
        if (avatars.size() > 0) {
            byte[] in = avatars.get(0).getBytes();
            RequestOptions options = new RequestOptions();
            Glide.with(this).load(in)
                    .apply(options.circleCrop())
                    .into(head);
        }
    }

    @SuppressLint("SetTextI18n")
    private void initList() {
        List<academic> academicList = MyApplication.getDaoInstant().getAcademicDao().loadAll();
        if (academicList.size() > 0) {
            academic a = academicList.get(0);
            if (StringUtil.isEmpty(a.getGpa(), a.getNotPass(), a.getPass(), a.getTotalCourse())) {
                MyApplication.getDaoInstant().getAcademicDao().deleteAll();
            } else {
                gpa.setText("GPA\n" + a.getGpa());
                zong.setText("总课程\n" + a.getTotalCourse());
                tg.setText("通过\n" + a.getPass());
                wg.setText("未过\n" + a.getNotPass());
            }
        }
    }

    public void onClick(View v) {
        if (!loading) {
            switch (v.getId()) {
                case R.id.cx_gr:
                    ToastUtil.showToast("😊里面没有数据啦");
                    break;
                case R.id.cx_cj:
                    UiUtils.startActivity(this, SearchGrades.class);
                    break;
                case R.id.cx_kc:
                    UiUtils.startActivity(this, SearchExam.class);
                    break;
                case R.id.cx_course:
                    DialogView.getCourse(JWXT_main.this, (save, year, term, dialog) -> save.setOnClickListener(v1 -> {
                        dialog.dismiss();
                        EventBus.getDefault().post(new MessageEvent("JWXT_main", 1, null));
                        int thisYear = 2016 + year.getValue();
                        int thisTerm = term.getValue() + 1;
                        course(stuNum, thisYear, thisTerm);
                    }));
                    break;
                case R.id.cx_nextcourse:
                    UiUtils.startActivity(this, SearchCourse.class);
                    break;
                case R.id.cx_kj:
                    UiUtils.startActivity(this, SearchKj.class);
                    break;
            }
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            super.onDestroy();
            this.finish();
        }
    }

    public void alertDialog(String title, String msg) {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle(title)
                .setMsg(msg)
                .setMsgGravity(false)
                .setNegativeButton("设置", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    UiUtils.startActivity(this, Setting.class);
                })
                .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                    finish();
                })
                .show();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("JWXT_main")) {
            switch (event.getWhat()) {
                case 1:
                    viewstub_loading.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("✌课程加载完成");
                    break;
                case 3:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦‍" + event.getMessage());
                    break;
                case 9:
                    initText();
                    initList();
                    EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                    viewstub_loading.setVisibility(View.GONE);
                    EventBus.getDefault().post(new MessageEvent("MainActivity", 5, null));
                    EventBus.getDefault().post(new MessageEvent("MainActivity", 10));
                    break;
                case 10:
                    initText();
                    initList();
                    EventBus.getDefault().post(new MessageEvent("MainActivity", 5, null));
                    break;
                case 11:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦‍数据由于网络不稳定走丢啦");
                    break;
                case 12:
                    viewstub_loading.setVisibility(View.GONE);
                    initList();
                    initText();
                    if (event.getRefresh() != null && event.getRefresh()) ToastUtil.showToast("✌认证完成");
                    break;
            }
        }
    }
}
